const {SyncHook} = require('tapable'); 

const eventEmitter = require('./common/eventbus');

const log = require('./common/log');

const message = require('./common/ansi');

const processError =require('./common/error');

const git = require('./src/git/index');

const writeTempData = require('./src/conf/writeTempData');

const {P_SERIES,OUTPUT_DIR,OUTPUT_NAME} = require('./common/constans');

const Pack = require('./src/pack/index');

const versionFile = require('./common/getVersionFile');

// 获取npm 的参数
const argv = require('yargs').argv

class Autopack{

  constructor(config){

    this.config = config || {};

    this.pack = null;

    // 生命周期钩子
    this.hooks={

      entryOption:new SyncHook(),

      beforeQuestion:new SyncHook(),

      finishQuestion:new SyncHook(),

      beforeTarball:new SyncHook(),

      finishTarball:new SyncHook(),

      packCompleted:new SyncHook(),

    }

    //获取插件列表
    let plugins= this.config.plugins;

    //判断有无插件
    if(Array.isArray(plugins)){

      plugins.forEach(plugin=>{

        //执行插件中的apply方法，每个插件都会有这个apply方法，如果你自定义过webpack插件应该能明白
        plugin.apply(this);

      });
      
    }

  }

  // 检查git环境
  checkoutGitEnv(){

    if(!git.check().result) processError('当前环境下git不可用，请检查git环境。确保您已安装git 并且已登录。');

    if(!git.checkStatus().result) processError('当前目录下git仓库不可用，请检查git仓库。当前的检测指令为 git status');

    // if(git.getLocalBranch().branch.startsWith('M'))processError('不能在M分支下进行自动打包程序');

  }

  // 向node环境添加数据
  addDataToEnv(version, branch){
    
    //let {config} = data;

    const config = versionFile(P_SERIES);

    let argvs = { version: version, branch: branch, platform: P_SERIES}

    log(0,`用户输入的配置：${JSON.stringify(argvs)}`)

    let {outputDir,outputName} = this.config;

    argvs[OUTPUT_DIR] = outputDir;

    argvs[OUTPUT_NAME] = outputName;

    let autopack_data={...argvs,mode: P_SERIES,config:this.config,versionConfig: config,cwd:process.cwd()}

    // 往全局环境添加数据
    process.env.autopack_data=JSON.stringify(autopack_data);

    writeTempData(autopack_data);

    return autopack_data;

  }

  init(){

    log(0,'',true);

    // 检查git环境
    this.checkoutGitEnv();

    console.log('版本号',argv._[0],argv._[1]);

    // 调用finish方法监听打包完成事件
    this.finish();

    this.hooks.beforeTarball.call();
    const envData = this.addDataToEnv(argv._[0],argv._[1]);
    this.pack = new Pack(envData);
    
  }

  finish(){

    eventEmitter.on('Autopack.finish',()=>{

      message.success('Autopack过程结束，程序退出');

      log(0,'',true);
      
      this.hooks.packCompleted.call();

      process.exit(0);
      
    });
  }

}

module.exports = Autopack;